﻿using System;
using System.Globalization;

namespace HttpServer.MVC.Rendering.Spark
{
    /// <summary>
    /// Generic data dictionary used for Spark views.
    /// </summary>
    /// <remarks>
    /// This is a reimplementation of ASP.NET MVC ViewDataDictionary, minus the ModelState stuff.
    /// </remarks>
    public class SparkDataDictionary<TModel> : SparkDataDictionary where TModel : class
    {
        public SparkDataDictionary() :
            base()
        {
        }

        public SparkDataDictionary(TModel model) :
            base(model)
        {
        }

        public SparkDataDictionary(SparkDataDictionary sparkDataDictionary) :
            base(sparkDataDictionary)
        {
        }

        public new TModel Model
        {
            get
            {
                return (TModel)base.Model;
            }
            set
            {
                SetModel(value);
            }
        }

        protected override void SetModel(object value)
        {
            TModel model = value as TModel;

            // If there was a value but the cast failed, throw an exception
            if ((value != null) && (model == null))
            {
                throw new InvalidOperationException(
                    String.Format(CultureInfo.CurrentUICulture,
                        "Cannot set model. The model was of the wrong type. We got {0} but expected {1}.", value.GetType(), typeof(TModel)));
            }

            base.SetModel(value);
        }
    }

}
